#!/usr/bin/env python
from lib.format_time import *
from lib.HandleMysql import *
from lib.switch_code import *
from prime_conn import *
from lib.load_data import *
import time
import math
import sys
import re
reload(sys)
sys.setdefaultencoding('utf-8')


def set_gbinfo_weight(date):
    
    stat_conn = set_stats_conn()
    open_conn = set_open_conn()
    gb_conn = set_gb_conn()
    
    default_weight = 20000000;    
    line_list = []
    cate_list = None
    src_list = None
    default_src = "t58com"
    lv_cates ={'25':'jiudian','16':'jinjiao','91':'guonei','92':'nongjia','93':'caizhai','94':'chujing','95':'piaoliu','96':'jingdian','97':'webquan','151':'huaxue','261':'zhoubian'}
    
    nav_dict = [0,1,2,3,4]
    #nav_dict = [0]
    query_tmp = "select strategyid,code,defaultval,variable,isarea,status from t_strategy where siteid=8;"
    ly_strat_list = open_conn.get_results(query_tmp)
                            
    query = "select cityid,groupbuyid,subtypeid as prodtypeid from hotindex group by groupbuyid ;"
    items = gb_conn.get_results(query)
    print "groupbuy count : %s \n" % len(items)
    for item in items:
        city_id = item[0]
        gb_id = item[1]
        type_id = item[2]
        #print type_id
        weight = default_weight
        #print "3.get gbinfo from groupbuyinfo"
        query_tmp = "select starttime,ordercount,salecount,successnum,groupprice,discount,salemaxnum,isagent,creator from groupbuyinfo where id=%s;"%gb_id
        items_tmp = gb_conn.get_results(query_tmp)
        if len(items_tmp) == 0:
            continue
        #print items_tmp
        start_time = items_tmp[0][0]
        order_count = items_tmp[0][3]
        sale_count = items_tmp[0][2]
        if sale_count < order_count:
            order_count = sale_count
            
        success_num = items_tmp[0][3]
        group_price = items_tmp[0][4]
        discount = items_tmp[0][5]
        sale_maxnum = items_tmp[0][6]
        is_agent = items_tmp[0][7]
        creator = items_tmp[0][8]
        #print order_count
        gb_visit = 0
        gb_rate =1
        gb_sales = 0
        gb_weight = 0
        query_tmp = "select visit,sales,weight,rate from t_gbaction where groupbuyid=%s;"%gb_id
        gb_action = open_conn.get_results(query_tmp)
        if len(gb_action) > 0:
            visit = gb_action[0][0]
            gb_sales = gb_action[0][1]
            gb_weight = gb_action[0][2]
            gb_rate = gb_action[0][3]
        
        start_ms = time.mktime(start_time.timetuple())
        #print start_ms
        weight = math.log(start_ms)
        diff = time.time() - start_ms
        #print diff
        days = diff/86400.0
        
        if days <= 1:
            days = 1
        elif days > 6:
            days = days * 1.5
        
        avg_count = order_count/days
        avg_visit = gb_visit/days
        
        visit_score = 1        
        if days > 1:
            if avg_count < 1:
                gb_rate = 0.9 * gb_rate
            elif avg_count < 5:
                gb_rate = 0.95 * gb_rate
            elif avg_count < 10:
                gb_rate = 0.97 * gb_rate
        
        if avg_visit < 1:
            avg_visit = 1
        visit_score = math.log(avg_visit)
        
        sales_score = avg_count*group_price
        if sales_score == 0:
            sales_score = 1
        if days == 1:
            if sales_score > 800:
                if group_price <800:
                    sales_score = 2* sales_score
            
        if avg_count == 0:
            if days == 1:
                if group_price < 500:
                    avg_count = 4
                else:
                    avg_count = 1
            else:
                avg_count = 1
                
        if avg_count > 100:
            avg_count += 100
        
        sys_score = set_gb_item_score(city_id,type_id,group_price,discount)
        if sys_score < 1:
            sys_score = 10
        
        #print days,order_count,sales_score,avg_count
        score = weight*1000000
        score += sys_score*200 +(visit_score + math.log(sales_score) * 1.23 + 1.03 * (math.log(avg_count)/(days*2)) )/920
        #print weight
        #each nav
        for site_id in nav_dict:
            weight = score
            #print weight
            #print "4.get site strategy"
            query_tmp = "select strategyid,code,defaultval,variable,isarea,status from t_strategy where siteid=%s;"%site_id
            strat_list = open_conn.get_results(query_tmp)
            for strat in strat_list:
                strat_id = strat[0]
                strat_code = strat[1]
                default_val = strat[2]
                variable  = strat[3]
                is_area = strat[4]
                status = strat[5]
                
                #xinpin
                if(days == 1 ):
                    if strat_code == "xinpin":
                        weight = weight *variable + default_val
                    elif strat_code == "xplinchen":
                        hour = int(get_last_hour())
                        if(hour < default_val):
                            weight = weight *variable
                #print weight
                #jiupin
                if strat_code == "jiupin":
                    if variable<days:
                        tms = days/variable
                        if default_val == 0:
                            default_val = 1000
                        weight = weight  - 1000*default_val * tms
                        if weight < 0:
                            weight = default_weight*0.75

                #chengshi
                #todo
                
                #leibie
                elif strat_code == "leibie":
                    val_str = 0
                    rate = 1
                    if cate_list is None:
                        query_tmp = "select keystr,valuestr,rate from t_strategyitem where strategyid=%s; "%strat_id
                        cate_list = open_conn.get_results(query_tmp)
                    for cate in cate_list:
                        key = cate[0]
                        if str(type_id) == key:
                            val_str = int(cate[1])
                            rate = cate[2]
                            break
                    weight = weight * rate + val_str
                #price & lingyuan gb
                elif strat_code == "lingyuan":
                    if group_price <= 0:
                        weight = weight *variable + default_val
                
                #discount
                #todo

                #maiguangle
                elif strat_code == "maiguangle":
                    weight = weight *variable + default_val
                
                #tuikuan
                elif strat_code == "tuikuan":
                    if order_count > 0:
                        refund_rate = gb_sales / order_count
                        
                        if refund_rate*100 > default_val:
                            weight = weight *variable
                
                #laiyuan
                elif strat_code == "laiyuan":
                    src_name = default_src
                    if is_agent == 101:
                        src_name = creator
                    elif is_agent == 2:
                        src_name = "dianpu"
                    
                    if src_list is None:
                        query_tmp = "select keystr,valuestr,rate from t_strategyitem where strategyid=%s; "%strat_id
                        src_list = open_conn.get_results(query_tmp)
                    val = 0
                    rate = 1
                    for src in src_list:
                        key = src[0]
                        if src_name == key:
                            val = int(src[1])
                            rate = src[2]
                            break                    
                    weight = (weight + val) * rate
                #lvyou
                elif strat_code == "lvyou":
                    #print "0"
                    #print days
                    if default_val == 1:        #use?
                        #print "1"
                        if lv_cates.has_key(str(type_id)):
                            #print "2"
                            for ly in ly_strat_list:
                                #xinpin
                                st_code = ly[1]
                                st_default_val = ly[2]
                                st_variable  = ly[3]
                                #print st_code,st_variable,st_default_val
                                if(days == 1 ):
                                    if st_code == "xinpin":
                                        weight = weight *st_variable + st_default_val
                                        #weight = weight + default_val
                                        #print weight
                                #xiaoshou
                                if st_code == "xiaoshou":
                                     #weight = weight *variable
                                     weight = weight*1.01 + st_default_val
                                     
                                #tousu
                                elif st_code == "tousu":
                                     #weight = weight *variable
                                     weight = weight + st_default_val
                                #tuikuan
                                elif st_code == "tuikuan":
                                     #weight = weight *variable
                                     weight = weight + st_default_val
                                #chaping
                                elif st_code == "chaping":
                                     #weight = weight *variable
                                     weight = weight + st_default_val
                                #haoping
                                elif st_code == "haoping":
                                     #weight = weight *variable
                                     weight = weight + st_default_val
                                #zhifu
                                elif st_code == "zhifu":
                                     #weight = weight *variable
                                     weight = weight + st_default_val
                #print strat_code,weight
                #print weight
                    
            #single
            #print days
            weight = weight*gb_rate
            
            if group_price > 400 :
                if site_id > 0:
                    weight = weight*0.9
                else:
                    weight = weight*0.98
            #
            if site_id == 1:
                if sale_count < 10000:
                    rr = sale_count/100000.0
                    weight = weight * (1+rr)
                if sale_count == 0:
                    if days > 1:
                        weight = weight*0.88
                    
            if avg_count > 50:
                weight += 2000*(avg_count/(50*days))
            #print weight
            param = [site_id,gb_id,weight]
            line_list.append('\t'.join(map(lambda i : str(i), param)))
            gbscore_update(gb_id,weight)
    
    cont = '\n'.join(line_list)
    path = "/work3/opt/analytic/lh_tmp_data/prime_data/"
    file_name = "gb_sort_%s.txt"%date.replace('-',"")
    writeTextToFile(path,file_name,"w",cont)
    
    #print file_path
    stat_table = "t_gbinfo_sort"
    query = "truncate table %s;"%stat_table
    open_conn.execute_sql(query)
    load_data(open_conn,path+file_name,stat_table,'\t')
    
    stat_conn.close()
    open_conn.close()
    gb_conn.close()

def set_gb_item_score(city_id,type_id,gb_price,discount):
    return -0.154780383*city_id + -0.140006557*type_id + -0.528155856 * gb_price  + 6.283404163*discount + 249.4484916
    

def gbscore_update(groupbuyid=0,weight=0):
    gb_conn = set_gb_conn()
    query = "select groupbuyid from groupbuy_score where groupbuyid = %s;" %groupbuyid
    gbscore = gb_conn.get_results(query)
    if len(gbscore) > 0:
        groupbuyid = gbscore[0][0]
        update = "update groupbuy_score set score = %s ,updateon = %s" %(groupbuyid,date)


def execute(date):
    
    set_gbinfo_weight(date)

def main():

   #date = '2012-05-28'
   #execute(date)   
   if len(sys.argv)==1:
        start_date=get_yesterday()
        end_date=start_date
   elif len(sys.argv)==2:
        start_date=format_date(sys.argv[1])
        end_date=start_date
   elif len(sys.argv)==3:
        start_date=format_date(sys.argv[1])
        end_date=format_date(sys.argv[2])
   stat_date=start_date
   while stat_date>=start_date and stat_date<=end_date:
        print "The program of the date of %s is beginning at %s " %(stat_date,get_now())
        #
        execute( stat_date) 
        print "The program of the date of %s is end at %s " %(stat_date,get_now())
        stat_date=var_date(stat_date)


if __name__=='__main__':
    
    #t=time.time()
    #print int(t*100)
    main()
